#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include "log_service.h"
#include "ev_base.h"
#include "ev_timer.h"

#define TEST_TIMER_NUM 10

static void timer_thread(void)
{
    std::vector<EvTimer> vec;

    // this is important !!!!
    vec.reserve(TEST_TIMER_NUM);

    for (uint32_t i = 1; i <= TEST_TIMER_NUM; i ++) {
        vec.emplace_back(i * 100);
        vec.back().setCallBack([i]() {
            auto logger = LogService::default_logger();
            logger->info("Timer {} triggered!", i);
        });
        vec.back().start();
    }

    EvTimer exit_timer;
    exit_timer.setCallBack([]() {
        auto logger = LogService::default_logger();
        logger->info("Exit timer triggered!");
        EvBase::getInstance()->exit(0);
    });
    exit_timer.start(TEST_TIMER_NUM * 100 + 500);

    // this sleep is important !!!!
    std::this_thread::sleep_for(std::chrono::milliseconds(TEST_TIMER_NUM * 100 + 1000));
    LogService::default_logger()->info("Timer thread exit !!!");
}

int main()
{
    /* init log service */
    int ret = LogService::init({LogService::COLOR_LOG});
    if (ret != 0) {
        std::cerr << "init log service failed" << std::endl;
        return -1;
    }

    std::thread t(timer_thread);

    /* run glob event loop */
    auto logger = LogService::default_logger();
    logger->info("Starting event loop ...");
    EvBase::getInstance()->run();
    logger->info("Event loop exit !!!");

    t.join();
    logger->info("Program exit !!!");

    return 0;
}
